package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;

public class Test4 {
    public static void main(String[] args) throws Exception {
        File dir = new File(
                Test4.class.getResource(".").toURI()
        );

        System.out.println(dir.getName());

        //通过当前类ReflectDemo7的类对象获取所在的包名
        String packageName = Test4.class.getPackage().getName();
        //获取ReflectDemo7.class文件所在的目录中所有.class文件
        File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
        for (File sub : subs) {
            //获取字节码文件的文件名
            String fileName = sub.getName();
            String className = fileName.substring(0, fileName.indexOf("."));

            Class cls = Class.forName(packageName + "." + className);
            if (cls.isAnnotationPresent(AutoRunClass.class)) {
                Object o = cls.newInstance();
                Method[] methods = cls.getMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AutoRunMethod.class)) {
                        System.out.println(method.getName() + ":被注解AutoRunMethod");
                        method.invoke(o);
                    }
                }
            }
        }
    }
}
